﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsMessageGlobal.Funcs;

namespace WindowsFormsMessageGlobal.UI
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void buttonSubMessage_Click(object sender, EventArgs e)
        {
            MessageManager.Instance.MessageReceived += Instance_MessageReceived;
        }

        private void textAppendText(TextBox textBox, string str)
        {
            if (textBox.InvokeRequired)
            {
                textBox.Invoke(new Action(() =>
                {
                    if (textBox.Text.Length > 1000)
                        textBox.Text = "";
                    textBox.AppendText(str);
                }));
            }
            else
            {
                if (textBox.Text.Length > 1000)
                    textBox.Text = "";
                textBox.AppendText(str);
            }
        }

        private void Instance_MessageReceived(Funcs.Message obj)
        {
            if (textBox1 != null && !textBox1.IsDisposed)
            {
                textAppendText(textBox1, obj.Content + Environment.NewLine);
            }
        }
        public class EntityClass
        {
            private WeakReference eventHandlerRef;

            public event EventHandler MyEvent
            {
                add
                {
                    if (eventHandlerRef == null)
                    {
                        eventHandlerRef = new WeakReference(value);
                    }
                    else if (!eventHandlerRef.IsAlive)
                    {
                        eventHandlerRef.Target = value;
                    }
                    else
                    {
                        throw new InvalidOperationException("Event can only have one subscriber");
                    }
                }
                remove
                {
                    if (eventHandlerRef?.Target == value)
                    {
                        eventHandlerRef.Target = null;
                    }
                }
            }

            public void RaiseEvent()
            {
                EventHandler handler = eventHandlerRef?.Target as EventHandler;
                handler?.Invoke(this, EventArgs.Empty);
            }
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageManager.Instance.MessageReceived += Instance_MessageReceived;
        }
    }
}
